package jk.fox.engine.listener;

import jk.fox.common.exception.runtime.RpcRunException;
import jk.fox.common.payload.server.Server;
import jk.fox.engine.RpcNodeDefinition;
import jk.fox.engine.context.RpcContext;
import jk.fox.engine.process.RpcContextAware;
import jk.fox.registry.register.NodeRegister;

import java.util.Map;

/**
 * @author cuichao
 * @Description: RpcServiceRegistryListener
 * @Date: create in 2020/6/4 23:21
 */
public class RpcServiceRegistryListener implements RpcServiceStartedListener,RpcContextAware {

    private NodeRegister register;
    private RpcContext context;

    public RpcServiceRegistryListener(NodeRegister register) {
        this.register = register;
    }

    @Override
    public void listen(Server server) {
        Map<String, RpcNodeDefinition> definitionObjects = context.rpcNodeDefinitions();
        try {
            for (String node : definitionObjects.keySet()) {
                register.registry(definitionObjects.get(node),server.address());
            }
        }catch (Exception e){
            throw new RpcRunException(e);
        }
    }

    @Override
    public void setRpcContext(RpcContext context) {
        this.context = context;
    }
}
